<template>
  <div class="company-user-list">
<!--    <global-title title="用户管理列表"></global-title>-->
    <ul class="global-operation-list">
      <li class="global-operation-left">
        <ul class="global-filter-list">
          <li class="global-filter-item">
            <h2 class="global-filter-item-title">账户：</h2>
            <el-input
              placeholder="请输入"
              v-model="searchForm.username"
              clearable
              @change="getPost"
            ></el-input>
          </li>
          <li class="global-filter-item">
            <h2 class="global-filter-item-title">账号状态：</h2>
            <el-select
                v-model="searchForm.status"
                placeholder="请选择"
                clearable
                filterable
                :loading="optionsData.roleLoading"
            >
              <el-option
                  v-for="item in typeData"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              >
              </el-option>
            </el-select>
          </li>
          <li class="global-filter-item">
            <h2 class="global-filter-item-title">角色：</h2>
            <el-select
              v-model="searchForm.roleId"
              placeholder="请选择"
              clearable
              filterable
              :loading="optionsData.roleLoading"
            >
              <el-option
                v-for="item in optionsData.roleList"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </li>
          <li class="global-filter-item">
            <el-button
              type="primary"
              class="global-filter-item-search"
              @click="rePosts"
              >搜索</el-button
            >
          </li>
        </ul>
        <div>
          <el-button
              type="primary"
              @click="addAccount"
              v-if="operationList.includes('add')"
          >创建新账号</el-button
          >
        </div>
      </li>
      <li class="global-operation-right">
        <!-- <el-button
          type="primary"
          class="global-operation-right-add"
          @click="addUser"
          v-if="operationList.includes('edit')"
          >新增</el-button
        > -->
        <!-- <el-button
          class="global-operation-right-export"
          v-if="operationList.includes('export')"
          @click="handleExport"
          >导出</el-button
        > -->

        <!--        <el-button class="global-operation-right-export" @click="handleDelAll"-->
        <!--          >删除用户</el-button-->
        <!--        >-->
      </li>
    </ul>
    <div class="global-table-content">
      <div class="global-table" v-loading="tableLoading" v-if="dataList && dataList.length > 0">
        <div class="list" v-for="(item,index) in dataList" :key="index">
          <div class="left">
            <img class="img" src="~images/pic.png" alt="">
            <div class="nav">
              <div class="text1">{{ item.username }}<span>{{ item.roleName }}</span></div>
              <div class="text3">
                <img style="width: 14px;height: 14px;margin-right: 10px" src="@/assets/images/CompanyUser3.png" alt="" />
                <div :class="item.status === 1 ? 'isStatus1' : 'isStatus2'">{{ item.status === 1 ? "启用" : "禁用" }}</div>
                <img style="width: 14px;height: 14px;margin-right: 10px" src="@/assets/images/CompanyUser4.png" alt="" />
                <div>创建时间：{{ item.createTime }}</div>
                <img style="width: 14px;height: 14px;margin-right: 10px" src="@/assets/images/CompanyUser4.png" alt="" />
                <div>最后登录时间：{{ item.lastLoginTime }}</div>
              </div>
            </div>
          </div>
          <div class="right">
            <el-button
                type="primary"
                @click="handleCommand('b', item)"
                v-if="operationList.includes('edit') && item.id != 7">编辑</el-button>
            <!-- <el-button
              type="primary"
              @click="handleCommand('a', item)"
              v-if="operationList.includes('permissionEdit') && item.id != 7">修改权限</el-button> -->
            <el-button
            type="warning"
              @click="handleCommand('e', item)"
              v-if="operationList.includes('editStatus') && item.status === 1 && item.id != 7">禁用</el-button>
            <el-button
            type="warning"
              @click="handleCommand('f', item)"
              v-if="operationList.includes('editStatus') && item.status === 2 && item.id != 7">启用</el-button>
            <el-button
            type="danger"
              @click="handleCommand('d', item)"
              v-if="operationList.includes('editStatus') && item.id != 7">删除</el-button>
            <el-button
            type="primary"
              @click="handleCommand('bind', item)"
              v-if="operationList.includes('bind')">{{'绑定小程序用户'}}</el-button>
          </div>
        </div>
      </div>
      <!-- 暂无数据~ -->
      <div
          class="no-data"
          v-else
          style="height: calc(100vh - 130px - 80px);display: flex;align-items: center;justify-content: center;flex-direction: column"
      >
        <img style="width: 265px;height: 120px;margin-bottom: 32px" src="@/assets/images/tyNoData.png" alt="" />
        <div style="font-size: 16px;color: #A5A9B5">暂无数据~</div>
      </div>
      <div class="global-page">
        <div class="global-page-left">
          <el-checkbox
            :indeterminate="isIndeterminate"
            v-model="checkAll"
            @change="handleCheckAllChange"
            :disabled="dataList.length === 0"
          ></el-checkbox>
          <!-- <el-button
            @click="handleDelAll"
            v-if="operationList.includes('del')"
            class="global-page-left-btn"
            >删除</el-button
          > -->
        </div>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :page-sizes="pageSizes"
          :page-size="pageSize"
          :current-page="pageNum"
          background
          layout="sizes, total, prev, pager, next"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>


    <el-dialog
      :title="editDialogForm.title"
      :visible.sync="editDialog"
      center
      width="700px"
      custom-class="global-form-dialog"
    >
      <el-form
        :model="editDialogForm"
        :rules="editDialogRules"
        ref="editDialogRules"
        label-width="120px"
        class="demo-ruleForm"
        autocomplete="off"
      >
        <el-form-item
          label="用户头像："
          prop="pic"
          v-if="editDialogForm.title !== '修改密码'"
        >
            <!-- <el-upload
                class="avatar-uploader"
                :multiple="false"
                action="/tanyuan/manager/fileUpload"
                :on-preview="handlePreview"
                :on-success="handleAvatarSuccess"
                :on-remove="handleRemove"
                :data="tokenData"
                :show-file-list="false"
          >
            <img v-if="editDialogForm.pic" :src="editDialogForm.pic" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div slot="tip" class="el-upload__tip">
              只能上传jpg/png文件
            </div>
          </el-upload> -->
          
          <el-upload
            class="avatar-uploader"
            action="/manager/pc/user/fileUpload"
            :show-file-list="false"
            :data="{ token: $store.state.token }"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="editDialogForm.pic" :src="editDialogForm.pic" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon" style="height: 100px;width: 100px;line-height: 100px !important"></i>
            <div slot="tip" class="el-upload__tip" style="color: #919baf">
              只能上传jpg/png文件，图片比例：690px*330px
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item
          label="用户名称："
          prop="username"
          v-if="editDialogForm.title !== '修改密码'"
        >
          <el-input
            v-model="editDialogForm.username"
            placeholder="请输入用户名，必须是3-11位之间的汉字、字母、数字、下划线"
            minlength="3"
            maxlength="11"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="角色："
          prop="roleId"
          v-if="editDialogForm.title !== '修改密码'"
        >
          <el-select
            v-model="editDialogForm.roleId"
            placeholder="请选择"
            clearable
            filterable
            :loading="optionsData.roleLoading"
          >
            <el-option
              v-for="item in optionsData.roleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>


        <el-form-item
          label="密码："
          prop="password"
          v-if="editDialogForm.title !== '编辑账号'"
        >
          <el-input
            v-model="editDialogForm.password"
            placeholder="请输入"
            @focus="changeInputType"
            :type="inputType"
            show-password
          ></el-input>
        </el-form-item>
        <el-form-item
          label="重复密码："
          prop="checkPassword"
          v-if="editDialogForm.title !== '编辑账号'"
        >
          <el-input
            v-model="editDialogForm.checkPassword"
            placeholder="请输入"
            @focus="changeInputType"
            :type="inputType"
          ></el-input>
        </el-form-item>
      </el-form>
      <div class="global-form-dialog-btn">
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="分配权限"
      :visible.sync="permissionDialog"
      center
      width="500px"
      custom-class="permission-dialog"
    >
      <div class="permission-dialog-tree">
        <el-tree
          @check="clickNode"
          :data="treeList"
          ref="tree"
          show-checkbox
          node-key="id"
          :default-expand-all="true"
          :default-checked-keys="idList"
          :props="defaultProps"
        >
        </el-tree>
      </div>
      <el-button
        class="permission-dialog-btn"
        type="primary"
        @click="getCheckedKeys"
        :loading="saveLoading"
        >保存</el-button
      >
    </el-dialog>

    <el-dialog
        :title="editDialogForm.title"
        :visible.sync="dialogVisible"
        width="1000px"
        :before-close="handleClose1"
        custom-class="dialog1"
    >
      <el-form :model="editDialogForm" :rules="editDialogRules" ref="editDialogRules" label-width="120px" class="demo-ruleForm">
        <el-form-item
            label="用户头像："
            prop="pic"
        >
          <el-upload
              class="avatar-uploader"
              :multiple="false"
              action="/manager/pc/user/fileUpload"
              :on-preview="handlePreview"
              :on-success="handleAvatarSuccess"
              :on-remove="handleRemove"
              :data="{ token: $store.state.token }"
              :show-file-list="false"
          >
            <img
                v-if="editDialogForm.pic"
                :src="editDialogForm.pic"
                class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件</div>
          </el-upload>
        </el-form-item>
        <el-row :gutter="24">
          <el-col :span="11">
            <el-form-item
                label="用户名称："
                prop="username"
            >
              <el-input
                  style="width: 300px;"
                  v-model="editDialogForm.username"
                  placeholder="请输入用户名"
                  minlength="3"
                  maxlength="11"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
                label="用户密码："
                :prop="editDialogForm.title !== '编辑账号' ? 'password' : 'password1'"
            >
              <el-input
                  style="width: 300px;"
                  v-model="editDialogForm.password"
                  placeholder="请输入"
                  show-password
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item
                label="所属角色："
                prop="roleId"
            >
              <el-select
                  style="width: 300px;"
                  v-model="editDialogForm.roleId"
                  placeholder="请选择"
                  clearable
                  filterable
                  multiple
                  :loading="optionsData.roleLoading"
              >
                <el-option
                    v-for="item in optionsData.roleList"
                    :key="item.id"
                    :label="item.roleName"
                    :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')">保存</el-button>
      </span>
    </el-dialog>


      <el-dialog
          title="绑定小程序用户"
          :visible.sync="showNormalUserDialog"
          width="500px"
          :before-close="handleCloseNormalUser"
          custom-class="dialog1"
      >
      
          <el-row :gutter="24">
            <el-col :span="12">
              <el-select
                style="width: 300px;"
                v-model="chooseNormalUserId"
                placeholder="请选择"
                clearable
                filterable
              >
                <el-option
                    v-for="item in normalUserList"
                    :key="item.id"
                    :label="item.nickName"
                    :value="item.id"
                >
                </el-option>
              </el-select>
            </el-col>
          </el-row>
          
        <span slot="footer" class="dialog-footer">
          <el-button @click="showNormalUserDialog = false">取消</el-button>
          <el-button type="primary" @click="bindNormal">保存</el-button>
        </span>
      </el-dialog>

  </div>
</template>

<script>
import API from "@/api/apiCompanyUser";
import APIUser from "@/api/apiUser";

export default {
  name: "CompanyUserList",
  props: {
    operationList: Array,
  },
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入用户名"));
      } else {
        callback();
      }
    };
    const validateTelephone = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入手机号"));
      } else if (!/^\d{11}$/.test(this.editDialogForm.telephone)) {
        callback(new Error("请输入正确的手机号"));
      } else {
        callback();
      }
    };
    const validatePass = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入密码"));
      } else if (!/^[0-9A-Za-z]{6,18}$/.test(this.editDialogForm.password)) {
        callback(new Error("输入用户名需限制在6-18位且没有中文"));
      } else {
        if (this.editDialogForm.checkPassword) {
          this.$refs.editDialogRules.validateField("checkPassword");
        }
        callback();
      }
    };
    const validatePass2 = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.editDialogForm.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      treeList: [],
      idList: [],
      currentId: null,
      defaultProps: {
        children: "children",
        label: "label",
      },
      companyData: null,
      inputType: "text", // 含有密码输入框时需要
      // 搜索条件
      searchForm: {
        sort: 2,
        company: null,
        username: null,
        telephone: null,
        roleId: null,
        status: null
      },
      // 表格相关
      isIndeterminate: false,
      checkAll: false,
      multipleSelection: [], // 多选
      editDialog: false, // 编辑弹窗
      editCloseIcon: false, // close展示
      editCloseColor: false, // close展示
      // 编辑弹窗表单
      editDialogForm: {
        title: "新增账号",
        userId: null,
        username: null,
        password: null,
        telephone: null,
        company: null,
        checkPassword: null,
        roleId: [],
        pic: "https://abc.landseabespoke.com/pic.svg",
        address: "",
        province: "",
        city: "",
        area: "",
        provinceList: []
      },
      editDialogRules: {
        // 编辑弹窗表单验证
        telephone: [
          { required: true, validator: validateTelephone, trigger: "blur" },
        ],
        username: [
          { required: true, validator: validateUsername, trigger: "blur" },
        ],
        company: [{ required: true, message: "请选择公司", trigger: "change" }],
        password: [
          { required: true, validator: validatePass, trigger: "blur" },
        ],
        checkPassword: [
          { required: true, validator: validatePass2, trigger: "blur" },
        ],
        roleId: [{ required: true, message: "请选择角色", trigger: "change" }],
      },
      // 下拉框列表
      optionsData: {
        companyDialogType: null, // 1 - 筛选弹窗 2 - 编辑弹窗
        companyDialog: false,
        roleLoading: true,
        roleList: [],
      },
      typeData: [
        {
          value: '2',
          label: '禁用'
        },
        {
          value: '1',
          label: '启用'
        }
      ],
      // 表格相关
      tableLoading: true,
      dataList: [],
      pageSize: 5,
      pageNum: 1,
      total: 0,
      pageSizes: [5, 10, 15, 20],
      // 权限弹窗
      permissionDialog: false,
      permissionList: [],
      tokenData: {
        token: "",
      },
      headPic: '',
      province: [],
      formData: {
        provinceList: [],
        cityList: [],
        districtList: [],
      },
      saveLoading: false,
      parentTotalNum: 10,
      addDialog: false,
      addDialogTitle: '',
      ruleForm: {
        maint_time: '',
        projectName: '',
        projectId: '',
        username: '',
        maint_content: '',
        explain: '',
        desction: '',
        id: '',
      },
      rules: {
        maint_content: [
          { required: true, message: '请输入内容', trigger: 'blur' }
        ],
        maint_time: [
          { type: 'date', required: true, message: '请选择日期', trigger: 'change' }
        ],
        projectName: [
          { required: true, message: '请选择项目', trigger: 'blur' }
        ]
      },
      editDialogTitle: '',
      dialogVisible: false,
      props: {
        lazy: true,
        lazyLoad: this.lazyLoad,
        children: 'childrenList',
      },
      normalUserList: [],
      showNormalUserDialog: false,
      chooseNormalUserId: null,
      chooseManagerUserId: null,
    };
  },
  watch: {
    $route(){
      this.tokenData.token = this.$store.state.token;
      this.getRoleList();
      // this.getProvince();
      if (this.$route.query.row) {
        let row = JSON.parse(this.$route.query.row);
        let roleList = row.roleId.split(",");
        roleList.forEach((item, index) => {
          roleList[index] = parseInt(item);
        });
        this.editDialogForm = {
          title: "编辑账号",
          userId: row.id,
          username: row.username,
          telephone: row.telephone,
          roleId: roleList,
          address: row.address,
          province: row.province,
          city: row.city,
          area: row.area,
          pic: row.pic,
          password: "",
        };
        this.dialogVisible = true
        // this.getCity();
        // this.getDistrict();
      } else if (this.$route.query.type && this.$route.query.type == 1) {
        this.getUserMsg();
      } else {
        // this.addUser();
      }
    }
  },
  activated(){
    this.tokenData.token = this.$store.state.token;
    this.getRoleList();
    this.saveLoading = false
    var type = localStorage.getItem("editUserType")
    if(type && type == 1){
      this.rePosts()
    }else if(type && type == 2){
      this.getPost()
    } else {
      this.tokenData.token = this.$store.state.token
      this.init();
    }
    localStorage.removeItem("editUserType")
    if (this.$route.query.row) {
      let row = JSON.parse(this.$route.query.row);
      let provinceList = []
      provinceList.push(row.province)
      provinceList.push(row.city)
      provinceList.push(row.area)
      let roleList = row.roleId.split(",");
      roleList.forEach((item, index) => {
        roleList[index] = parseInt(item);
      });
      this.editDialogForm = {
        title: "编辑账号",
        userId: row.id,
        username: row.username,
        telephone: row.telephone,
        company: {
          companyName: row.company_name,
          id: row.company_id,
        },
        roleId: roleList,
        address: row.address,
        province: row.province,
        city: row.city,
        area: row.area,
        pic: row.pic,
        password: "",
        provinceList: provinceList
      };
      this.dialogVisible = true
    } else if (this.$route.query.type && this.$route.query.type == 1) {
      this.getUserMsg();
    } else {
      // this.addUser();
    }
  },
  mounted() {
    this.tokenData.token = this.$store.state.token
    this.init();
  },
  methods: {
    bindNormal(){
      const params = {
        token: this.$store.state.token,
        userId: this.chooseManagerUserId,
        appUserId: this.chooseNormalUserId,
      };
      API.doBindNormalUser(params).then((res) => {
        if (res.key === 1000) {
          this.$message({
            type: "success",
            message: "绑定成功",
          });
          this.showNormalUserDialog = false
          this.chooseNormalUserId = null
          this.chooseManagerUserId = null
          this.getPost()
        }
        this.$bus.$emit("show-loading", false);
      });
    },
    handleCloseNormalUser(){
      this.showNormalUserDialog = false
    },
    getNormalUserList(val){
      this.normalUserList = []
      const params = {
        token: this.$store.state.token,
      };
      APIUser.getNormalUserList(params).then((res) => {
        if (res.key === 1000) {
          res = res.result;
          this.normalUserList = res.list
          if(val && val == 1){
            this.showNormalUserDialog = true
          }
        }
        this.$bus.$emit("show-loading", false);
      });
    },
    beforeAvatarUpload(){},
    addAccount () {
      this.editDialogForm = {
        title: "新增账号",
        userId: null,
        username: null,
        password: null,
        telephone: null,
        company: null,
        checkPassword: null,
        roleId: [],
        pic: "https://abc.landseabespoke.com/pic.svg",
        address: "",
        province: "",
        city: "",
        area: "",
        provinceList: []
      };
      setTimeout(() => {
        this.$refs.editDialogRules.resetFields();
      },30)
      this.dialogVisible = true
    },
    submitForm () {
      this.$refs.editDialogRules.validate((valid) => {
        if (!valid) return;
        if (this.editDialogForm.title === "修改密码") {
          if (!this.editDialogForm.userId) {
            this.$message({
              type: "success",
              message: "操作失败，请刷新页面后重试",
            });
            return
          }
          this.saveLoading = true
          this.handleChangePassword();
        } else {
          this.saveLoading = true
          this.handleEdit();
        }
      });
    },
    lazyLoad(node, resolve) {
      let that = this
      setTimeout(() => {
        that.getProvince(node, resolve)
      }, 100)
    },
    getUserMsg() {
      this.$bus.$emit("show-loading", true);
      const params = {
        token: this.$store.state.token,
      };
      API.getManagerUserMsg(params).then((res) => {
        if (res.key === 1000) {
          res = res.result.data;
          let row = res;
          let provinceList = []
          provinceList.push(row.province)
          provinceList.push(row.city)
          provinceList.push(row.area)
          let roleList = row.roleId.split(",");
          roleList.forEach((item, index) => {
            roleList[index] = parseInt(item);
          });
          this.editDialogForm = {
            title: "编辑账号",
            userId: row.id,
            username: row.username,
            telephone: row.telephone,
            company: {
              companyName: row.company_name,
              id: row.company_id,
            },
            roleId: roleList,
            address: row.address,
            province: row.province,
            city: row.city,
            area: row.area,
            pic: row.pic,
            password: "",
            provinceList: provinceList
          };
          this.dialogVisible = true
          this.getCity();
          this.getDistrict();
        }
        this.$bus.$emit("show-loading", false);
      });
    },
    handleClose1 () {
      this.dialogVisible = false
    },
    changeProvince() {
      if(this.editDialogForm.city){
        this.editDialogForm.city = null
      }
      if(this.editDialogForm.area){
        this.editDialogForm.area = null
      }
      this.formData.cityList = [];
      this.formData.districtList = [];
      this.getCity();
    },
    changeCity() {
      if(this.editDialogForm.area){
        this.editDialogForm.area = null
      }
      this.formData.districtList = [];
      this.getDistrict();
    },
    getCity() {
      this.$bus.$emit("show-loading", true);
      const params = {
        token: this.$store.state.token,
        province: this.editDialogForm.province,
      };
      API.get_city(params).then((res) => {
        if (res.key === 1000) {
          res = res.result.list;
          this.formData.cityList = res;
        }
        this.$bus.$emit("show-loading", false);
      });
    },
    getDistrict() {
      this.$bus.$emit("show-loading", true);
      const params = {
        token: this.$store.state.token,
        province: this.editDialogForm.province,
        city: this.editDialogForm.city,
      };
      API.get_district(params).then((res) => {
        if (res.key === 1000) {
          res = res.result.list;
          this.formData.districtList = res;
        }
        this.$bus.$emit("show-loading", false);
      });
    },
    // 获取省市区
    getProvince(node,resolve){
      if(node.level == 0){
        let params = {
          token: this.$store.state.token,
        };
        API.get_province(params).then((res) => {
          if (res.key === 1000) {
            var list = res.result.list
            var provinceList = []
            list.forEach((item) => {
              var obj = {
                name: item,
                label: item,
                value: item,
                loading: false,
                childrenList: [],
                type: 1,
              }
              provinceList.push(obj)
            })
            resolve(provinceList)
          }
        });
      }else if(node.level == 1){
        let params = {
          token: this.$store.state.token,
          province: node.label
        };
        API.get_city(params).then((res) => {
          if (res.key === 1000) {
            let arr = [];
            if (res.result.list) {
              res.result.list.forEach((it) => {
                arr.push({
                  label: it,
                  value: it,
                  name: it,
                  loading: false,
                  childrenList: [],
                });
              });
            }
            resolve(arr)
          }
        });
      }else if(node.level == 2){
        let params = {
          token: this.$store.state.token,
          city: node.label
        };
        API.get_district(params).then((res) => {
          if (res.key === 1000) {
            let arr = [];
            if (res.result.list) {
              res.result.list.forEach((it) => {
                arr.push({
                  label: it,
                  value: it,
                  name: it,
                  loading: false,
                  //这句代码表示当点击最后一级的时候 label后面不会转圈圈 并把相关值赋值到选择器上
                  leaf: node.level >= 1,
                });
              });
            }
            resolve(arr)
          }
        });
      }
    },
    handleRemove(file, fileList) {
      console.log(file,fileList)
    },
    handleAvatarSuccess: function(e) {
      if(e.key == 1000){
        this.editDialogForm.pic = e.result.data.path;
        // this.headPic = e.result.data.path;
        this.$message.success({
          showClose: true,
          message: "上传成功",
          duration: 1500
        });
      }
    },
    handlePreview(file) {
      console.log(file)
    },
    changeSort(e) {
      // e.order descending-降序-2 ascending-正序-1
      if (e.order === "descending") {
        this.searchForm.sort = 2;
      } else if (e.order === "ascending") {
        this.searchForm.sort = 1;
      } else {
        this.searchForm.sort = null;
      }
      this.rePosts();
    },
    formatterTime(row) {
      return this.$moment(row.create_time).format("YYYY-MM-DD HH:mm:ss");
    },
    editLeave() {
      this.editCloseIcon = false;
      this.editCloseColor = false;
    },
    editEnter() {
      if (this.editDialogForm.company) {
        this.editCloseIcon = true;
        this.editCloseColor = true;
      }
    },
    clearSearchCompany() {
      // 清除搜索栏公司信息
      this.searchForm.company = null;
    },
    clearEditCompany() {
      // 清除编辑弹窗
      this.editDialogForm.company = null;
      this.editCloseColor = false;
      this.$refs.editDialogRules.validateField("company");
    },
    companySearchDialog() {
      // 打开搜索栏弹窗
      this.companyData = this.searchForm.company;
      this.optionsData.companyDialogType = 1;
      this.optionsData.companyDialog = true;
    },
    companyEditDialog() {
      // 打开编辑弹窗
      this.companyData = this.editDialogForm.company;
      this.optionsData.companyDialogType = 2;
      this.optionsData.companyDialog = true;
    },
    changeCompany(company) {
      if (this.optionsData.companyDialogType === 1) {
        this.optionsData.companyDialog = false;
        this.searchForm.company = company;
      } else if (this.optionsData.companyDialogType === 2) {
        this.optionsData.companyDialog = false;
        this.editDialogForm.company = company;
        this.$refs.editDialogRules.validateField("company");
      }
    },
    // 全局初始化
    init() {
      this.companyData = null;
      // 搜索条件重置
      this.searchForm = {
        username: null,
        telephone: null,
        company: null,
      };
      this.editDialog = false; // 初始化弹窗
      this.idList = [];
      this.permissionList = []; // 初始化权限列表
      this.rePosts();
      this.getRoleList();
    },
    // 防止密码自动输入
    changeInputType() {
      this.inputType = "password";
    },
    // 新增账号按钮
    addUser() {
      this.editDialogForm = {
        title: "新增账号",
        userId: null,
        username: null,
        telephone: null,
        company: null,
        roleId: [],
        pic: "https://abc.landseabespoke.com/pic.svg",
        address: "",
        province: "",
        city: "",
        area: "",
      };
      this.$nextTick(() => {
        this.$refs.editDialogRules.clearValidate();
      });
      this.getProvince();
      this.editDialog = true;
    },
    handleClose() {
      this.addDialog = false;
    },
    // 表单操作项
    handleCommand(e, row) {
      if (e === "a") {
        this.currentId = row.id;
        this.$router.push({
          path: '/upCompanyUser',
          query: {
            id: row.id
          }
        })
        // this.getPermission(row.id);
      } else if (e === "b") {
        setTimeout(() => {
          this.$refs.editDialogRules.clearValidate();
        }, 30);
        let provinceList = []
        provinceList.push(row.province)
        provinceList.push(row.city)
        provinceList.push(row.area)
        let roleList = row.roleId.split(",");
        roleList.forEach((item, index) => {
          roleList[index] = parseInt(item);
        });
        this.editDialogForm = {
          title: "编辑账号",
          userId: row.id,
          username: row.username,
          telephone: row.telephone,
          company: {
            companyName: row.company_name,
            id: row.company_id,
          },
          roleId: roleList,
          address: row.address,
          province: row.province,
          city: row.city,
          area: row.area,
          pic: row.pic,
          password: "",
          provinceList: provinceList
        };
        this.dialogVisible = true
      } else if (e === "c") {
        this.editDialog = true;
        this.editDialogForm = {
          title: "修改密码",
          userId: row.id,
        };
      } else if (e === "d") {
        const ids = [row.id];
        this.handleStatus(ids, 10);
      } else if (e === "e") {
        const ids = [row.id];
        this.handleStatus(ids, 2);
      } else if (e === "f") {
        const ids = [row.id];
        this.handleStatus(ids, 1);
      } else if(e === "view"){
        this.$emit("changeType", row)
      } else if (e === "bind") {
        this.chooseManagerUserId = row.id
        console.log(row)
        if(row.bindUserId){
          this.chooseNormalUserId = row.bindUserId
        }
        this.getNormalUserList(1)
      }
    },
    // 表单选择
    handleSelectionChange(val) {
      this.multipleSelection = val;
      // console.log(val);
    },
    // toastClose(done) {
    //   this.$confirm("确认关闭？")
    //     .then(() => {
    //       done();
    //     })
    //     .catch(() => {});
    // },
    // 分页pageSize改变
    handleSizeChange(e) {
      this.pageSize = e;
      this.rePosts();
    },
    // 分页pageNum改变
    handleCurrentChange(e) {
      this.pageNum = e;
      this.getPost();
    },
    // 重新请求
    rePosts() {
      this.pageNum = 1;
      this.dataList = [];
      this.getPost();
    },
    // 表格列表
    getPost() {
      this.tableLoading = true;
      const params = {
        token: this.$store.state.token,
        pageNum: this.pageNum,
        pageSize: this.pageSize,
      };
      if (this.searchForm.username) {
        params.keyword = this.searchForm.username;
      }
      if (this.searchForm.status && this.searchForm.status) {
        params.status = this.searchForm.status;
      }
      if (this.searchForm.roleId && this.searchForm.roleId) {
        params.roleId = this.searchForm.roleId;
      }
      API.adminUserList(params).then((res) => {
        if (res.key === 1000) {
          res = res.result;
          this.parentTotalNum = res.data
          this.total = res.count;
          res.list.forEach(item => {
            item.createTime = this.$moment(item.createTime).format("YYYY-MM-DD HH:mm:ss");
            item.lastLoginTime = this.$moment(item.lastLoginTime).format("YYYY-MM-DD HH:mm:ss");
          })
          this.dataList = res.list;
          this.tableLoading = false;
        }
      });
    },
    // 编辑账号信息接口
    handleConfirm() {
      this.$refs.editDialogRules.validate((valid) => {
        if (!valid) return;
        if (this.editDialogForm.title === "修改密码") {
          if (!this.editDialogForm.userId) {
            this.$message({
              type: "success",
              message: "操作失败，请刷新页面后重试",
            });
          }
          this.handleChangePassword();
        } else {
          this.handleEdit();
        }
      });
    },
    handleEdit() {
      this.$bus.$emit("show-loading", true);
      const params = {
        title: this.editDialogForm.title,
        username: this.editDialogForm.username,
        id: this.editDialogForm.id,
      }
      params.token = this.$store.state.token;
      params.realname = params.username;
      if (this.editDialogForm.userId) {
        params.userId = this.editDialogForm.userId;
      }

      params.password = this.editDialogForm.password;
      if (this.editDialogForm.roleId && this.editDialogForm.roleId.length > 0) {
        params.roleId = this.editDialogForm.roleId.join(",")
      }
      if(this.editDialogForm.userId){
        API.doUpAdminUser(params).then((res) => {
          if (res.key === 1000) {
            this.$message({
              type: "success",
              message: "编辑账号成功",
            });
            localStorage.setItem("editUserType", 2);
            this.dialogVisible = false;
            this.getPost()
          }
          this.saveLoading = false;
          this.$bus.$emit("show-loading", false);
        });
      }else{
        API.doAddAdminUser(params).then((res) => {
          if (res.key === 1000) {
            this.$message({
              type: "success",
              message: "新增账号成功",
            });
            localStorage.setItem("editUserType", 1);
            this.dialogVisible = false;
            this.getPost()
          }
          this.saveLoading = false;
          this.$bus.$emit("show-loading", false);
        });
      }
    },
    handleChangePassword() {
      this.$bus.$emit("show-loading", true);
      const params = {
        token: this.$store.state.token,
        password: this.editDialogForm.password,
        userId: this.editDialogForm.userId,
      };
      API.changePassword(params).then((res) => {
        if (res.key === 1000) {
          this.getPost();
          this.editDialog = false;
          this.$message({
            type: "success",
            message: "修改密码成功",
          });
        }
        this.$bus.$emit("show-loading", false);
      });
    },
    // 编辑弹窗关闭
    handleEditDialogClose() {
      this.editDialog = false;
      this.$refs.editDialogRules.resetFields();
    },
    // 删除全部按钮
    handleDelAll() {
      if (this.multipleSelection && this.multipleSelection.length > 0) {
        const ids = this.multipleSelection.map((item) => item.id);
        this.handleStatus(ids, 10);
      } else {
        this.$message({
          type: "warning",
          message: "请至少选择一项",
        });
      }
    },
    // 删除接口
    handleStatus(ids, status) {
      // status 1-启用 2-禁用 3-删除
      let title;
      if (status === 1) {
        title = "启用";
      } else if (status === 2) {
        title = "禁用";
      } else if (status === 10) {
        title = "删除";
      }
      this.$confirm("此操作将" + title + "该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.$bus.$emit("show-loading", true);
        const params = {
          token: this.$store.state.token,
          status,
        };
        params.userIds = ids.join(",");
        API.doUpAdminUserStatus(params).then((res) => {
          if (res.key === 1000) {
            this.$message({
              type: "success",
              message: title + "成功",
            });
          }
          if (status === 3) {
            this.rePosts();
          } else {
            this.getPost();
          }
          this.$bus.$emit("show-loading", false);
        });
      });
      // .catch(() => {
      //   this.$message({
      //     type: "info",
      //     message: "已取消" + title
      //   });
      // });
    },
    // 权限窗口关闭
    // handlePermissionDialogClose() {
    //   this.permissionDialog = false;
    // },
    // 获取权限列表
    getPermission(id) {
      this.idList = [];
      this.$bus.$emit("show-loading", true);
      const params = {
        token: this.$store.state.token,
        userId: id,
      };
      API.getUserPermissionList(params).then((res) => {
        if (res.key === 1000) {
          res = res.result.list;
          this.permissionList = res;
          let treeList = [];
          const idList = [];
          res.forEach((firstItem) => {
            const firstObj = {
              id: "x" + firstItem.id,
              label: firstItem.powerName,
            };
            if (firstItem.list && firstItem.list.length > 0) {
              firstObj.children = [
                {
                  id: firstItem.id,
                  label: firstItem.powerName,
                },
              ];
              if (firstItem.isChoose === 1) {
                idList.push(firstItem.id);
              }
              let bol = true;
              firstItem.list &&
                firstItem.list.forEach((secondItem) => {
                  if (secondItem.buttonId) {
                    const secondObj = {
                      id: secondItem.buttonId,
                      label: secondItem.buttonName,
                    };
                    firstObj.children.push(secondObj);
                  }
                  if (secondItem.isChooseButton === 1) {
                    idList.push(secondItem.buttonId);
                  } else if (secondItem.isChooseButton === 0) {
                    bol = false;
                  }
                });
              if (bol) {
                idList.push(firstItem.id);
              }
            }
            treeList.push(firstObj);
          });
          this.treeList = treeList;
          this.idList = idList;

          this.permissionDialog = true;
        }
        this.$bus.$emit("show-loading", false);
      });
    },
    getCheckedKeys() {
      this.saveLoading = true
      const idList = this.$refs.tree.getCheckedKeys();
      const params = {
        token: this.$store.state.token,
        userId: this.currentId,
        powerIds: JSON.stringify(idList.filter((item) => item[0] !== "x")),
      };
      API.upPermission(params).then((res) => {
        if (res.key === 1000) {
          this.permissionDialog = false;
          this.$message({
            type: "success",
            message: "分配成功",
          });
          this.saveLoading = false
        }
      });
    },
    clickNode(node, { checkedKeys }) {
      let currentId = node.id;
      if (currentId[0] === "x") return; // 选中父级 无需操作
      let parentItem;
      this.treeList.some((firstItem) => {
        if (!firstItem.children) return false;
        // if (firstItem.children[0] === currentId) return true;
        return firstItem.children.some((secondItem) => {
          if (secondItem.id === currentId) {
            parentItem = firstItem;
            return true;
          }
          return false;
        });
      });
      if (parentItem) {
        if (parentItem.children[0].id === currentId) {
          const idList = checkedKeys;
          if (!checkedKeys.includes(currentId)) {
            parentItem.children.forEach((item) => {
              let index = idList.indexOf(item.id);
              if (index > -1) {
                idList.splice(index, 1);
              }
            });
            this.$refs.tree.setCheckedKeys(idList);
          }
        } else {
          if (checkedKeys.includes(currentId)) {
            const idList = checkedKeys;
            console.log(idList.toString());
            idList.push(parentItem.children[0].id);
            console.log(idList.toString());
            this.$refs.tree.setCheckedKeys(idList);
          } else {
            const idList = checkedKeys;
            let bol = parentItem.children.some((item) =>
              idList.includes(item.id)
            );
            if (!bol) {
              let index = idList.indexOf(parentItem.id);
              if (index > -1) {
                idList.splice(index, 1);
                this.$refs.tree.setCheckedKeys(idList);
              }
            }
          }
        }
      }
    },
    getRoleList() {
      const params = {
        token: this.$store.state.token,
      };
      API.getAllRoleList(params).then((res) => {
        if (res.key === 1000) {
          this.optionsData.roleLoading = false;
          this.optionsData.roleList = res.result.list;
        }
      });
    },
    // 全选
    handleCheckAllChange() {
      this.$refs.multipleTable.toggleAllSelection();
    },
    //导出
    handleExport() {
      this.$bus.$emit("show-loading", true);
      const params = {
        token: this.$store.state.token,
      };
      if (this.searchForm.telephone) {
        params.telephone = this.searchForm.telephone;
      }
      if (this.searchForm.username) {
        params.username = this.searchForm.username;
      }
      if (this.searchForm.company && this.searchForm.company.id) {
        params.companyId = this.searchForm.company.id;
      }
      API.getExportCompanyUserList(params).then((res) => {
        if (res) {
          const content = res.data;
          const blob = new Blob([content]);
          // 从response的headers中获取filename,
          // 后端response.setHeader("Content-disposition", "attachment; filename=xxxx.docx") 设置的文件名;
          var contentDisposition = res.headers["content-disposition"];
          var patt = new RegExp("filename=([^;]+\\.[^\\.;]+);*");
          var result = patt.exec(contentDisposition);
          const fileName = decodeURI(result[1]);
          if ("download" in document.createElement("a")) {
            // 非IE下载
            const elink = document.createElement("a");
            elink.download = fileName;
            elink.style.display = "none";
            elink.href = URL.createObjectURL(blob);
            document.body.appendChild(elink);
            elink.click();
            URL.revokeObjectURL(elink.href); // 释放URL 对象
            document.body.removeChild(elink);
          } else {
            // IE10+下载
            navigator.msSaveBlob(blob, fileName);
          }
        }
        this.$bus.$emit("show-loading", false);
      });
    },
  },
};
</script>

<style lang="sass">
.avatar-uploader
    .el-upload
      border: 1px dashed #d9d9d9
      border-radius: 6px
      cursor: pointer
      position: relative
      overflow: hidden
      &:hover
        border-color: #409eff
      .avatar-uploader-icon
        font-size: 28px
        color: #8c939d
        width: 100px
        height: 100px
        line-height: 100px !important
        text-align: center
      .avatar
        width: 100px
        height: 100px
        display: block
</style>
<style lang="sass" scoped>
.global-operation-list
  padding-left: 0
.global-select .global-select-btn
  background: #FFFFFF
.global-table-content
  padding: 0
.company-user-list
  //@include container
  .isStatus1
    width: 41px
    height: 21px
    background: #F1FFFC
    border-radius: 3px
    border: 1px solid #03C192
    font-size: 14px!important
    color: #03C192!important
    line-height: 21px
    text-align: center
  .isStatus2
    width: 41px
    height: 21px
    background: #FFF2F2
    border-radius: 3px
    border: 1px solid #F46565
    font-size: 14px!important
    color: #F44141!important
    line-height: 21px
    text-align: center
  .global-operation-left
    margin-right: 0
  ::v-deep .permission-dialog
    .el-dialog__body
      display: flex
      align-items: center
      flex-direction: column
      padding: 30px 60px
      .permission-dialog-tree
        width: 100%
        max-height: 450px
        overflow-y: auto
        overflow-x: hidden
        margin-bottom: 40px
  .global-table
    display: flex
    align-items: center
    justify-content: center
    flex-direction: column
    .list
      background: #FFFFFF
      box-shadow: 0px 0px 10px 0px rgba(93, 139, 198, 0.05)
      border-radius: 14px
      margin-bottom: 15px
      width: 100%
      display: flex
      align-items: center
      justify-content: space-between
      padding: 19px 24px
      .left
        display: flex
        align-items: center
        .img
          width: 90px
          height: 90px
          border-radius: 4px
          margin-right: 17px
        .nav
          .text1
            font-size: 20px
            font-weight: bold
            color: #222222
            line-height: 26px
            display: flex
            align-items: center
            justify-content: flex-start
            margin-bottom: 16px
            span
              height: 16px
              background: #FFF8ED
              border-radius: 11px
              border: 1px solid #FF9901
              font-size: 12px
              color: #FF9901
              line-height: 16px
              padding: 0 8px
              display: block
              text-align: center
              margin-left: 11px
          .text2
            display: flex
            align-items: center
            justify-content: flex-start
            margin-bottom: 25px
            i
              font-size: 20px
              color: #1861FD
              margin-right: 7px
            .text2_1
              font-size: 14px
              color: #222222
              line-height: 19px
              margin-right: 7px
            .text2_2
              margin-left: 5px
              font-size: 23px
              font-weight: bold
              color: #222222
              line-height: 29px
              margin-right: 3px
            .text2_3
              font-size: 14px
              color: #B5B5C3
              line-height: 19px
          .text3
            display: flex
            align-items: center
            i
              font-size: 14px
              color: #B5B5C3
              margin-right: 5px
            div
              font-size: 14px
              color: #B5B5C3
              line-height: 19px
              margin-right: 80px
      .right
//.permission-dialog-item
//  background: #f2f2f2

</style>
